﻿    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using Microsoft.SharePoint;
using Truextend.Common.Data;
using Truextend.CoffeShop.Model;
using Truextend.CoffeShop.Bussiness.Interfaces;

namespace Truextend.CoffeShop.Bussiness
{
    public class OrderManager : Repository<Order> , IOrderManager
    {
        IDetailManager detailManager = null;

        public OrderManager(IUnitOfWork unitOfWork , IDetailManager detailManager) : base(unitOfWork) {
            this.detailManager = detailManager;
        }
        
        public IList<Order> GetOrdersForState(string state)
        {
            var context = (CoffeShopEntities)Context;

            var info = from p in context.Order where p.State == state select p;

            return info.ToList();
        }

        public void AddOrder(Order order , IList<int> listProductsId)
        {
            this.Add(order);

            //Order lastOrder = GetLastOrder();
            //order.Detail = new System.Data.Objects.DataClasses.EntityCollection<Detail>();
            //var d = new Detail(){
            //    Order=order,
            //    Product= mp.
            //};
            //order.Detail.Add(d)


            foreach (int productId in listProductsId) { 
                Detail detail = new Detail();
                detail.Order=order;
                detailManager.AddDetailForProductID(detail, productId);
            }                                    
        }

        public void ChangeStateOfAnOrder(Order order, string state) 
        {
            var context = (CoffeShopEntities)Context;
            order = this.GetOrderById(order.OrderId);
            order.State = state;
            this.Save();
        }

        public void DeleteOrder(Order order) 
        {
            var context = (CoffeShopEntities)Context;
            //order.Detail = new System.Data.Objects.DataClasses.EntityCollection<Detail>();
            IList<Detail> listDetails = detailManager.GetAllDetailsOfAnOrder(order.OrderId);
            
            foreach(var detail in listDetails){
                
                try {
                    var listConsumptions = (from p in context.Consumption
                                            where p.Detail.DetailId == detail.DetailId
                                            select p).ToList();
                    foreach (var consumtpion in listConsumptions) {
                        context.DeleteObject(consumtpion);
                    }
                
                } catch(Exception){}

                context.DeleteObject(detail);
            }
            
            this.Save();
        }

        public Order GetLastOrder()
        {
            var context = (CoffeShopEntities)Context;

            var info = from p in context.Order orderby p.OrderId descending select p;

            return info.First();
        }

        public Order GetOrderById(int orderId)
        {
            var context = (CoffeShopEntities)Context;

            var info = from p in context.Order where p.OrderId == orderId select p;

            return info.First();
        }

        public void CloseOrderReception(List<string> allEmails)
        {
            var context = (CoffeShopEntities) Context;

            var expiredOrders = from o in context.Order
                                where o.State == "INP" && o.EndDate < DateTime.Now
                                select o;
            foreach (var expiredOrder in expiredOrders)
            {
                expiredOrder.State = "COM";
                SendNotification(expiredOrder,allEmails,"Completed order: "+ expiredOrder.Title);
            }

            context.SaveChanges();
        }

        public void StartOrderReception(List<string> allEmails)
        {
            var context = (CoffeShopEntities)Context;

            var expiredOrders = from o in context.Order
                                where o.State == "CRE" && o.StartDate <= DateTime.Now && o.EndDate >= DateTime.Now
                                select o;
            foreach (var expiredOrder in expiredOrders)
            {                

                expiredOrder.State = "INP";   
                SendNotification(expiredOrder,allEmails, "New Order: "+expiredOrder.Title);             
            }

            context.SaveChanges();
        }

        private void SendNotification(Order expiredOrder, List<string> allEmailAddress, string subject)
        {
            try
            {
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Host = "imail.truextend.com";
                smtpClient.Credentials = new System.Net.NetworkCredential("oscar.cardenas@truextend.com", "123qwe!@#");
                smtpClient.Port = 25;

                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress("administrator@truextend.com");

                foreach (var email in allEmailAddress)
                {
                    if (email != "")
                    {
                        MailAddress mailAddress = new MailAddress(email);
                        mailMessage.To.Add(mailAddress);
                    }
                }

                mailMessage.Subject = subject;

                mailMessage.IsBodyHtml = true;
                mailMessage.Body = "There is an current order: <br/>" +
                                   " Title: " + expiredOrder.Title + "<br />" +                                   
                                   " Start Date: " + expiredOrder.StartDate + "<br />" +
                                   " End Date: " + expiredOrder.EndDate;

                smtpClient.Send(mailMessage);
            }
            catch (Exception)
            {                
                throw;
            }
        }
    }
}
